package com.qsl.ssyx.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.qsl.ssyx.common.Interceptor.AuthContextHolder;
import com.qsl.ssyx.common.constant.RedisConst;
import com.qsl.ssyx.common.exception.BusinessException;
import com.qsl.ssyx.common.result.Result;
import com.qsl.ssyx.common.result.ResultCodeEnum;
import com.qsl.ssyx.common.utils.JwtHelper;
import com.qsl.ssyx.enums.UserType;
import com.qsl.ssyx.enums.user.User;
import com.qsl.ssyx.user.service.UserService;
import com.qsl.ssyx.user.utils.HttpClientUtils;
import com.qsl.ssyx.user.utils.WXPublicAccount;
import com.qsl.ssyx.vo.user.LeaderAddressVo;
import com.qsl.ssyx.vo.user.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Api(tags = "微信小程序接口")
@RestController
@RequestMapping("/api/user/weixin")
public class WeiXinApiControlle {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @ApiOperation("微信小程序授权登录-微信获取openid(小程序)登录")
    @GetMapping("/wxLogin/{code}")  // code ==> 0d3XPj000iAVBQ1cjb0008zzoA0XPj0G
    public Result longinWx(@ApiParam(value = "code", required = true) @PathVariable String code) {
        // 1.获取微信返回code临时值(2个小时)
        // 2. 获取code + 小程序id + 小程序秘钥，get请求微信接口服务
        // 拼接get请求地址
        StringBuffer url = new StringBuffer();
        url.append("https://api.weixin.qq.com/sns/jscode2session") // https://api.weixin.qq.com/sns/jscode2session
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String tokenUrl = String.format(url.toString(), WXPublicAccount.ACCESS_KEY_ID, WXPublicAccount.ACCESS_KEY_SECRET, code);

        // HttpClient发送get请求
        String result = null;
        try {
            result = HttpClientUtils.get(tokenUrl);
        } catch (Exception e) {
            throw new BusinessException(ResultCodeEnum.FETCH_ACCESSTOKEN_FAILD);
        }

        // 3.获取微信接口返回值 session_key 和 openid
        JSONObject jsonObject = JSONObject.parseObject(result);
        String session_key = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");


        // 4. 根据openid判断是否第一次使用微信授权登录，第一次添加信息到user表
        User user = userService.getUserByOpenId(openid);
        log.error("=>>>>>>>>>>>", user);
        if (user == null) {
            user = new User();
            user.setOpenId(openid);
            user.setNickName(openid);
            user.setPhotoUrl("");
            user.setUserType(UserType.USER);
            user.setIsNew(0); // 是否新用户
            userService.save(user);
        }

        // 5.根据userId查询提货点和团长信息
        ////提货点  user表  user_delivery表
        ////团长    leader表
        LeaderAddressVo leaderAddressVo = userService.getLeaderAddressByUserId(user.getId());

        // 6.使用JWT工具根据userId和userName生成token字符串
        String token = JwtHelper.createToken(user.getId(), user.getNickName());

        // 5. 根据userId获取当前登录用户信息，存放到Redis里设置过期时间
        UserLoginVo userLoginVo = userService.getUserLoginVo(user.getId());
        // key,用户信息，过期时间，日期
        redisTemplate.opsForValue()
                .set(RedisConst.USER_LOGIN_KEY_PREFIX + user.getId(),
                        userLoginVo,
                        RedisConst.USERKEY_TIMEOUT,
                        TimeUnit.DAYS);

        // 6. 封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("token", token);
        map.put("leaderAddressVo", leaderAddressVo);
        return Result.ok(map);
    }

    @ApiOperation(value = "跟新用户昵称与头像")
    @PostMapping("/auth/updateUser")
    public Result updateUser(@RequestBody User user) {
        // 获取当前登录用户ID
        User user1 = userService.getById(AuthContextHolder.getUserId());
        // 把昵称更新为微信用户   replaceAll: 替换  把表情替换为*号
        user1.setNickName(user.getNickName().replaceAll("[ue000-uefff]", "*"));
        user1.setPhotoUrl(user.getPhotoUrl());
        userService.updateById(user1);
        return Result.ok(null);
    }
}
